const { src, dest, series, watch } = require('gulp')
const browserSync = require('browser-sync').create()
const reload = browserSync.reload
const del = require('del')
//gulp-uglify => plugins.uglify
const plugins = require('gulp-load-plugins')()
//压缩js 文件
function js(cb) {
  src('js/*.js')
    .pipe(plugins.uglify())
    .pipe(dest('./dist/js'))
    .pipe(
      reload({
        stream: true,
      })
    )
  cb()
}

//压缩css 文件
function css(cb) {
  src('css/*.scss')
    .pipe(plugins.sass({ outputStyle: 'compressed' }))
    .pipe(
      plugins
        .autoprefixer({
          cascade: false,
          remove: false,
        })
        .pipe(dest('./dist/css'))
    )
    .pipe(
      reload({
        stream: true,
      })
    )
  cb()
}

//监听文件变化
function watcher() {
  watch('js/*.js', js)
  watch('css/*.scss', css)
}

// 清除dist目录
function clean(cb) {
  del('./dist')
  cb()
}

// server
function serve(cb) {
  browserSync.init({
    server: {
      baseDir: './',
    },
  })
  cb()
}
exports.scripts = js
exports.styles = css
exports.clean = clean
exports.default = series([clean, js, css, serve, watcher])
